package com.ruubypay.web.core.generator.plugins;

import com.ruubypay.web.core.generator.entity.ColumnEntity;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.config.Context;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Desc : 视图层自动生产工具
 * @author sucyun
 * Date :2018/3/17 下午3:54
 */
public class ViewGeneratorPlugin {


	/**
	 * Desc : 自动生成页面文件
	 * @author sucyun 
	 * Date :2018/3/17 下午4:55
	 */
	public void generator(String domainObjectName,IntrospectedTable introspectedTable,String targetPath){
		String domainFirstLowerName = domainObjectName.substring(0, 1).toLowerCase() + domainObjectName.substring(1, domainObjectName.length());
		List<ColumnEntity> columnEntityList = new ArrayList<>();
		List<IntrospectedColumn> introspectedColumns = getColumnsInThisClass(introspectedTable);
		for (IntrospectedColumn column : introspectedColumns) {
			ColumnEntity columnEntity = new ColumnEntity();
			columnEntity.setAttrChName(column.getRemarks());
			columnEntity.setAttrEnName(column.getJavaProperty());
			columnEntity.setColumnName(column.getActualColumnName());
			columnEntity.setRemark(column.getRemarks());
			columnEntity.setType(column.getFullyQualifiedJavaType().getShortName());
			columnEntityList.add(columnEntity);
		}
		Map<String, Object> root = new HashMap<>(1);
		root.put("columnMap",columnEntityList);
		root.put("entityName",domainObjectName);
		root.put("entityLowerName",domainObjectName.toLowerCase());
		root.put("entityFirstLowerName",domainFirstLowerName);
		FreeMarkerUtil util = new FreeMarkerUtil();

		util.viewTemplatePrint(domainObjectName,"template-list.ftl",targetPath,root,domainObjectName.toLowerCase()+"_list.jsp");
		util.viewTemplatePrint(domainObjectName,"template-form.ftl",targetPath,root,domainObjectName.toLowerCase()+"_form.jsp");
	}
	private List<IntrospectedColumn> getColumnsInThisClass(IntrospectedTable introspectedTable) {
		List<IntrospectedColumn> introspectedColumns;
		if (includePrimaryKeyColumns(introspectedTable)) {
			if (includeBLOBColumns(introspectedTable)) {
				introspectedColumns = introspectedTable.getAllColumns();
			} else {
				introspectedColumns = introspectedTable.getNonBLOBColumns();
			}
		} else {
			if (includeBLOBColumns(introspectedTable)) {
				introspectedColumns = introspectedTable.getNonPrimaryKeyColumns();
			} else {
				introspectedColumns = introspectedTable.getBaseColumns();
			}
		}
		return introspectedColumns;
	}
	private boolean includeBLOBColumns(IntrospectedTable introspectedTable) {
		return !introspectedTable.hasBLOBColumns();
	}
	private boolean includePrimaryKeyColumns(IntrospectedTable introspectedTable) {
		return !introspectedTable.hasPrimaryKeyColumns();
	}
}
